<template>
  <div>
    <div class="navbar-div">
      <van-nav-bar title="购物车" />
    </div>
    <div class="card-title">
      <van-button size="small" type="danger" @click="clearCart" plain>清空购物车</van-button>
    </div>
    <!--显示购物车中的商品-->
    <div class="cart-list">
      <div class="pang-row" v-for="(item,index) in cartInfo" :key="index">
        <div class="pang-img">
          <img :src="item.image" width="100%" />
        </div>
        <div class="pang-text">
          <div class="pang-goods-name">{{item.Name}}</div>

          <div class="pang-control">
            <van-stepper v-model="item.count" />
          </div>
        </div>
        <div class="pang-goods-price">
          <div>x{{item.count}}</div>
          <div class="allPrice">￥{{item.price*item.count | moneyFilter}}</div>
        </div>
      </div>
       <div class="totalMoney">商品总价：￥ {{totalMoney | moneyFilter}}</div>
    </div>
  </div>
</template>

<script>
import { toMoney } from "@/filter/moneyFilter.js";
export default {
  data() {
    return {
      cartInfo: [], //购物车数据
      isEmpty: false //购物车数据状态
    };
  },
  filters: {
    moneyFilter(money) {
      return toMoney(money);
    }
  },
  created() {
    this.getCartInfo();
  },
  methods: {
    getCartInfo() {
      //判断缓存里是否有添加的商品数据
      if (localStorage.cartInfo) {
        //localStorage、parse、stringify连在一起用。
        this.cartInfo = JSON.parse(localStorage.cartInfo); //parse把字符串转化为js对象
      }
      console.log("this.cartInfo:" + JSON.stringify(this.cartInfo)); //stringify把对象转化为字符串
      this.isEmpty = this.cartInfo.length ? true : false; //三目运算，根据是否有数据判断购物车状态。
    },
    clearCart() {
      //清空购物车缓存
      localStorage.removeItem("cartInfo");
      this.cartInfo = [];
    }
  },
  //计算商品总价格
  computed:{
     totalMoney(){
         let allPrice = 0
         this.cartInfo.forEach((item,index) => {
             allPrice += item.count*item.price
         });
         localStorage.cartInfo = JSON.stringify(this.cartInfo)//购物车商品信息变化后进行重新保存
         return allPrice
     }
  }
};
</script>

<style scoped>
.card-title {
  height: 2rem;
  line-height: 2rem;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 5px;
  text-align: right;
}
.cart-list {
  background-color: #fff;
}
.pang-row {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  padding: 0.5rem;
  font-size: 0.85rem;
  border-bottom: 1px solid #e4e7ed;
}
.pang-img {
  flex: 6;
}
.pang-text {
  flex: 14;
  padding-left: 10px;
}
.pang-control {
  padding-top: 10px;
}
.pang-goods-price {
  flex: 4;
  text-align: right;
}
.allPrice {
  color: #f44;
}
.totalMoney {
  text-align: right;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 5px;
}
</style>